package com.daisuxia.web.controller;

import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import redis.clients.jedis.JedisCluster;

import com.daisuxia.back.test.SerializeUtil;
import com.daisuxia.back.utils.DwzResult;
import com.daisuxia.back.utils.RequestUtils;
import com.daisuxia.back.utils.ServiceResult;
import com.daisuxia.back.utils.SpringUtils;
import com.daisuxia.back.utils.SysCacheUtils;
import com.daisuxia.constant.Constant;
import com.daisuxia.web.common.reslult.Status;
import com.daisuxia.web.dao.IIndexDao;
import com.daisuxia.web.pojo.BackConfigParams;
import com.daisuxia.web.pojo.BackUser;
import com.daisuxia.web.pojo.User;
import com.daisuxia.web.service.IInfoIndexService;
import com.octo.captcha.service.image.ImageCaptchaService;

public class BaseController {

    public static final String MESSAGE = "message";
    public static final String LOGING_DEVICE_PREFIX = "device_";
    public static final int FRONT_USER_EXIST_TIME = 259200;//3*24*60*60
    public static final int BACK_USER_EXIST_TIME = 259200;//3*24*60*60

//    public static final int CODE_ERROR = -1 ;//错误信息
//    public static final int CODE_WAITING = -3 ;//等待信息
//    public static final int CODE_UNLOGIN = -2 ;//未登录
//    public static final int CODE_SUCCESS = 0 ;//请求成功

    private static Logger loger = Logger.getLogger(BaseController.class);

    @Autowired
    JedisCluster jedisCluster;
    @Autowired
    private IInfoIndexService infoIndexService;
    @Autowired
    private IIndexDao indexDao;

    /**
     * 得到 session
     *
     * @return
     */
    protected HttpSession getSession(HttpServletRequest request) {
        return request.getSession();
    }

    /**
     * 获取IP地址
     *
     * @param request
     * @return
     */
    public String getIpAddr(HttpServletRequest request) {
        return RequestUtils.getIpAddr(request);
    }

    @Autowired
    private ImageCaptchaService captchaService;

    /**
     * 得到session中的admin user对象
     */
    public BackUser loginAdminUser(HttpServletRequest request) {


        if (request == null) {
            request = ((ServletRequestAttributes) RequestContextHolder
                    .getRequestAttributes()).getRequest();
        }
        byte[] userInfo = jedisCluster.get(request.getSession().getId().getBytes());
        BackUser backUser = (BackUser) SerializeUtil.unserialize(userInfo);


//		BackUser backUser = (BackUser) request.getSession().getAttribute(
//				Constant.BACK_USER);
        return backUser;
    }

//	/**
//	 * 得到session中的admin user对象
//	 */
//	public User loginFrontUser(HttpServletRequest request) {
//		if (request == null) {
//			request = ((ServletRequestAttributes) RequestContextHolder
//					.getRequestAttributes()).getRequest();
//		}
//		User zbUser = (User) request.getSession().getAttribute(
//				Constant.FRONT_USER);
//		return zbUser;
//	}

    /**
     * 获取APP的配置参数
     * @param appName
     * @param param
     * @return
     */
    public String getAppConfig(String appName, String param) {
        if(StringUtils.isBlank(appName)){
            appName = BackConfigParams.DSX;
        }
        Map<String, String> map = SysCacheUtils.getConfigMap(appName);
        String config = map.get(param+"_"+appName);
//        loger.error("appName=" + appName + " param=" + param + " result=" + config);
        return config;
    }

	public ServiceResult check(HttpServletRequest request, String phone) {
		Map<String, String> map = SysCacheUtils.getConfigMap(BackConfigParams.SMSCODE);
		int phoneLimit = Integer.valueOf(map.get("PHONE_LIMIT"));
		int ipLimit = Integer.valueOf(map.get("IP_LIMIT"));
		String ip = RequestUtils.getIpAddr();
		String key = "CODE_TYPE_PHONE_" + phone;
		int time = 60 * 60 * 24;
		String phoneTimes = jedisCluster.get(key);
		int phones = 0;
		if (phoneTimes != null) {
			phones = Integer.valueOf(phoneTimes);
			if (phones >= phoneLimit) {
				return new ServiceResult("500", "当日验证码发送达到上限，请24小时后重试！");
			}
		}
		phones += 1;
		String key2 = "CODE_TYPE_IP_" + ip;
		String ipTimes = jedisCluster.get(key2);
		int ips = 0;
		if (ipTimes != null) {
			ips = Integer.valueOf(ipTimes);
			if (ips >= ipLimit) {
				return new ServiceResult("500", "IP受限，请24小时后重试！");
			}
		}
		ips += 1;
		jedisCluster.setex(key, time, phones + "");
		jedisCluster.setex(key2, time, ips + "");
		return new ServiceResult(ServiceResult.SUCCESS, "允许发送");
	}
    public User loginFrontUserByDeiceId(HttpServletRequest request, HttpServletResponse response){
        String deviceId = request.getParameter("deviceId");
        String telephone = request.getParameter("mobilePhone");
        loger.info("设备号deviceId=" + deviceId);
        loger.info("手机号码：" + telephone);
        if (StringUtils.isBlank(deviceId)) {
            renderUnLogin(response);
            return null;
        }
        byte[] userInfo;
        if(StringUtils.isNoneBlank(telephone)){
            userInfo = jedisCluster.get((LOGING_DEVICE_PREFIX + deviceId + telephone).getBytes());
        }
        else{
            userInfo = jedisCluster.get((LOGING_DEVICE_PREFIX + deviceId).getBytes());
        }
        if (null == userInfo) {
            renderUnLogin(response);
            return null;
        }
        else{
            User zbUser = (User) SerializeUtil.unserialize(userInfo);
            loger.info("loginFrontUserByDeiceId1 key :" + (LOGING_DEVICE_PREFIX + deviceId + telephone) + ",userId:" + zbUser.getId());
            return zbUser;
        }
    }

    public User loginFrontUserByDeiceId(HttpServletRequest request) {
        String deviceId = request.getParameter("deviceId");
        String telephone = request.getParameter("mobilePhone");
        loger.info("设备号deviceId=" + deviceId);
        loger.info("手机号码：" + telephone);
        if (StringUtils.isBlank(deviceId)) {
            return null;
        }
        byte[] userInfo = null;
        if(StringUtils.isNoneBlank(telephone)){
            userInfo = jedisCluster.get((LOGING_DEVICE_PREFIX + deviceId + telephone).getBytes());
        }
        else{
            userInfo = jedisCluster.get((LOGING_DEVICE_PREFIX + deviceId).getBytes());
        }

        if (null == userInfo) {
            return null;
        }
        User zbUser = (User) SerializeUtil.unserialize(userInfo);
        loger.info("loginFrontUserByDeiceId2 key :" + (LOGING_DEVICE_PREFIX + deviceId + telephone) + ",userId:" + zbUser.getId());
        return zbUser;
    }


    public void loginSucc(HttpServletRequest request, User user) {
        String deviceId = request.getParameter("deviceId");
        String telephone = request.getParameter("mobilePhone");
        if (StringUtils.isBlank(deviceId)) {
            System.out.println("loginSucc deviceId is null");
            return;
        }

        if (null == user) {
            System.out.println("loginSucc user is null");
            return;
        }

        User usernew = new User();
        usernew.setId(user.getId());

        byte[] usrSerialize = SerializeUtil.serialize(usernew);
        if(null != telephone){
            jedisCluster.set((LOGING_DEVICE_PREFIX + deviceId + user.getUserName()).getBytes(), usrSerialize);
            jedisCluster.expire((LOGING_DEVICE_PREFIX + deviceId + user.getUserName()).getBytes(), FRONT_USER_EXIST_TIME);
            loger.info("loginFrontUserByDeiceId new app 2.0 key :" + (LOGING_DEVICE_PREFIX + deviceId + user.getUserName()) + ",userId:" + user.getId());
        }
        else{
            jedisCluster.set((LOGING_DEVICE_PREFIX + deviceId).getBytes(), usrSerialize);
            jedisCluster.expire((LOGING_DEVICE_PREFIX + deviceId).getBytes(), FRONT_USER_EXIST_TIME);
            loger.info("loginFrontUserByDeiceId3 key :" + (LOGING_DEVICE_PREFIX + deviceId) + ",userId:" + user.getId());
        }

        this.infoIndexService.addInfoIndexInfo(usernew);//初始化动态表
    }

    public void backloginSucc(HttpServletRequest request, BackUser user) {
//		String deviceId = request.getParameter("deviceId");

//		if(StringUtils.isBlank(deviceId)){
//			System.out.println("loginSucc deviceId is null");
//			return ;
//		}

        byte[] usrSerialize = SerializeUtil.serialize(user);
        jedisCluster.set(request.getSession().getId().getBytes(), usrSerialize);
        jedisCluster.expire(request.getSession().getId().getBytes(), BACK_USER_EXIST_TIME);


    }

    public void backloginOut(HttpServletRequest request) {
//		String deviceId = request.getParameter("deviceId");
//		
//		if(StringUtils.isBlank(deviceId)){
//			System.out.println("loginSucc is null");
//			return ;
//		}
        //删除redis中用户动态数据
        byte[] userInfo = jedisCluster.get(request.getSession().getId().getBytes());
        BackUser user = (BackUser) SerializeUtil.unserialize(userInfo);
        if (null != user) {
            jedisCluster.del(request.getSession().getId().getBytes());
        }

//		jedisCluster.del(request.getSession().getId().getBytes());
    }

    public void loginOut(HttpServletRequest request) {
        String deviceId = request.getParameter("deviceId");
         String telephone = request.getParameter("mobilePhone");
         loger.info("退出登录:"+telephone);
        if (StringUtils.isBlank(deviceId)) {
            System.out.println("loginSucc is null");
            return;
        }
        //删除redis中用户动态数据
        byte[] userInfo;
        if(null != telephone){
            userInfo = jedisCluster.get((LOGING_DEVICE_PREFIX + deviceId + telephone).getBytes());
            jedisCluster.del((LOGING_DEVICE_PREFIX + deviceId + telephone).getBytes());
        }
        else{
            userInfo = jedisCluster.get((LOGING_DEVICE_PREFIX + deviceId).getBytes());
            jedisCluster.del((LOGING_DEVICE_PREFIX + deviceId).getBytes());
        }
        User user = (User) SerializeUtil.unserialize(userInfo);
        if (null != user) {
            jedisCluster.del(Constant.CACHE_INDEX_INFO_KEY + user.getId());
            //删除用户缓存
            HashMap hashMap = new HashMap();
            hashMap.put("userId",user.getId());
            indexDao.delIndexUser(hashMap);
        }
    }


    /**
     * 验证码
     *
     * @param request
     * @param response
     * @return
     */
    public boolean validateSubmit(HttpServletRequest request,
                                  HttpServletResponse response) {
		try {
			//解开注释注释掉下面添加的极为原来的
//			return captchaService.validateResponseForID(request.getSession(
//					false).getId(), request.getParameter("captcha")
//					.toLowerCase());
			
			
			//20170312  zjb  添加   去掉session缓存，改为redis缓存，解决负载均衡session不共享问题
			//---------------------------------------------------------------------------------------
			String RCaptchaKey=request.getParameter("RCaptchaKey");
			String captcha=jedisCluster.get(RCaptchaKey);
			if(captcha!=null&&captcha.equals(request.getParameter("captcha").toLowerCase())){
				jedisCluster.del(RCaptchaKey);
				return true;
			}else{
				return false;
			}
			//---------------------------------------------------------------------------------------
		} catch (Exception e) {
			return false;
		}
	}

    /**
     * 获得request中的参数
     *
     * @param request
     * @return string object类型的map
     */
    public HashMap<String, Object> getParametersO(HttpServletRequest request) {
        HashMap<String, Object> hashMap = new HashMap<String, Object>();
        if (request == null) {
            request = ((ServletRequestAttributes) RequestContextHolder
                    .getRequestAttributes()).getRequest();
        }
        Map req = request.getParameterMap();
        if ((req != null) && (!req.isEmpty())) {
            Map<String, Object> p = new HashMap<String, Object>();
            Collection keys = req.keySet();
            for (Iterator i = keys.iterator(); i.hasNext(); ) {
                String key = (String) i.next();
                Object value = req.get(key);
                Object v = null;
                if ((value.getClass().isArray())
                        && (((Object[]) value).length > 0)) {
                    if (((Object[]) value).length > 1) {
                        v = ((Object[]) value);
                    } else {
                        v = ((Object[]) value)[0];
                    }
                } else {
                    v = value;
                }
                if ((v != null) && ((v instanceof String)) && !"\"\"".equals(v)) {
                    String s = ((String) v).trim();
                    if (s.length() > 0) {
                        p.put(key, s);
                    }
                }
            }
            hashMap.putAll(p);
            // 读取cookie
            hashMap.putAll(ReadCookieMap(request));

        }
        return hashMap;
    }

    /**
     * 得到页面传递的参数封装成map
     */

    public Map<String, String> getParameters(HttpServletRequest request) {
        if (request == null) {
            request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        }
        Map<String, String> p = new HashMap<String, String>();
        Map req = request.getParameterMap();
        if ((req != null) && (!req.isEmpty())) {

            Collection keys = req.keySet();
            for (Iterator i = keys.iterator(); i.hasNext(); ) {
                String key = (String) i.next();
                Object value = req.get(key);
                Object v = null;
                if ((value.getClass().isArray())
                        && (((Object[]) value).length > 0)) {
                    v = ((Object[]) value)[0];
                } else {
                    v = value;
                }
                if ((v != null) && ((v instanceof String)) && !"\"\"".equals(v)) {
                    String s = (String) v;
                    if (s.length() > 0) {
                        p.put(key, s);
                    }
                }
            }
            //读取cookie
            p.putAll(ReadCookieMap(request));
            return p;
        }
        return p;
    }

    /**
     * 将cookie封装到Map里面
     *
     * @param request
     * @return
     */
    private static Map<String, String> ReadCookieMap(HttpServletRequest request) {
        Map<String, String> cookieMap = new HashMap<String, String>();
        Cookie[] cookies = request.getCookies();
        if (null != cookies) {
            for (Cookie cookie : cookies) {
                cookieMap.put(cookie.getName(), cookie.getValue());
            }
        }
        return cookieMap;
    }


    /**
     * @param key
     * @param flag
     * @return true:设置成功（代表是没有超发），false：设置失败（超发）
     */
    public Long checkForFront(String key, String flag) {
        return checkForFront(key, flag, 15);
    }

    public Long checkForFront(String key, String flag, int time) {
        loger.info("checkForFront key:" + key + ",flag:" + flag);
        String expireKey = key + flag;
        loger.info("checkForFront expireKey:" + expireKey);
        Long remainTime = jedisCluster.ttl(expireKey);
        loger.info("checkForFront key:" + expireKey + ",result:" + remainTime);
        if (remainTime <= 0) {
            jedisCluster.setnx(expireKey, "1");
            jedisCluster.expire(expireKey, time);
        }
        return remainTime;
    }

    public boolean delCheckForFront(String key, String flag) {
        /*loger.info("delCheckForFront key:"+key+",flag:"+flag);
		String expireKey = key+flag;
		loger.info("delCheckForFront expireKey:"+expireKey);
		jedisCluster.del(expireKey);*/
        return true;
    }

    /**
     * 返回未登录状态
     */
    public static void renderUnLogin(HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("code", Status.LOGIN.getName());
        result.put("message", "请先登录");
        SpringUtils.renderJson(response, result);
    }


    /**
     * 返回成功数据
     */
    public static void renderAppJson(HttpServletResponse response, Object obj, String message) {
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("code", Status.SUCCESS.getName());
        result.put("message", null != message ? message : "请求成功");
        result.put("data", obj);
        SpringUtils.renderJson(response, result);
    }

    /**
     * 返回成功数据
     */
    public static void renderAppJson(HttpServletResponse response, Object obj) {
        renderAppJson(response, obj, null);
    }

}
